package com.nova.bluetooth.helpUtils;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;

public class NetworkUtil {
    /**
     * 检测网络连接状态
     *
     * @param context
     * @return
     */
    public static boolean isNetworkConnected(Context context) {
        if (context != null) {
            ConnectivityManager mConnectivityManager = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
            if (mNetworkInfo != null) {
                return mNetworkInfo.isAvailable();
            }
        }
        return false;
    }

    /**
     * 网络是否未连接
     * <p>未连接时给出提示</p>
     *
     * @param context
     * @return boolean 是否连接网络
     */
    public static boolean isNetDisconnected(Context context) {
        if (!isNetworkConnected(context)) {
            return true;
        }
        return false;
    }

    /**
     * 判断用户是否连接在wifi下
     *
     * @param context
     * @return
     */
    public static boolean isConnectedByWifi(Context context) {
        ConnectivityManager mConnectivityManager = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = mConnectivityManager.getActiveNetworkInfo();
        if (networkInfo != null) {
            return networkInfo.getType() == ConnectivityManager.TYPE_WIFI ? true : false;
        }
        return false;
    }

    /**
     * 网络延时检测
     * @param host  检测网络地址
     * @return
     */
    public static long getPingTime(String host) {
        try {
            InetAddress inet = InetAddress.getByName(host);
            long startTime = System.nanoTime();
            boolean reachable = inet.isReachable(5000); // 超时时间设置为5000毫秒
            long endTime = System.nanoTime();
            if (reachable) {
                return (endTime - startTime) / 1000000; // 转换为毫秒
            } else {
                System.out.println("Host is not reachable");
                return -1;
            }
        } catch (UnknownHostException e) {
            System.err.println("Unknown host: " + host);
            return -1;
        } catch (IOException e) {
            System.err.println("IO Exception while trying to reach host: " + host);
            return -1;
        }
    }
}
